package com.zyj.exam_app.testPaper_manager.service.impl;

import com.zyj.exam_app.question_manager.service.QuestionService;
import com.zyj.exam_app.testPaper_manager.bean.PaperQuestionBean;
import com.zyj.exam_app.testPaper_manager.bean.TestPaperBean;
import com.zyj.exam_app.testPaper_manager.mapper.PaperQuestionMapper;
import com.zyj.exam_app.testPaper_manager.mapper.TestPaperMapper;
import com.zyj.exam_app.testPaper_manager.service.TestPaperService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Component
public class TestPaperServiceImpl implements TestPaperService {

    @Autowired
    private TestPaperMapper testPaperMapper;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;

    @Autowired
    private QuestionService questionService;

    @Override
    public List<TestPaperBean> findAllTestPapers() {
        return testPaperMapper.findAllTestPapers();
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT,
            rollbackForClassName = {"com.zyj.exam_app.exception.ServiceException"}, propagation = Propagation.REQUIRED)
    public boolean deleteOneTestPaperById(String testPaperId) {
        //校验参数
        if(StringUtils.isBlank(testPaperId)){
            //抛出异常ServiceException
        }
        //删除试卷
        testPaperMapper.deleteOneTestPaperById(testPaperId);
        //删除试卷考题信息
        int deleteNum = paperQuestionMapper.deleteByTestPaperId(testPaperId);
        return true;
    }

    @Override
    @Transactional(readOnly = false, isolation = Isolation.DEFAULT,
            rollbackForClassName = {"com.zyj.exam_app.exception.ServiceException"}, propagation = Propagation.REQUIRED)
    public void addOneTestPaper(TestPaperBean testPaper) {
        //新增试卷
        testPaperMapper.insertOneTestPaper(testPaper);
        //新增考题
        if(CollectionUtils.isNotEmpty(testPaper.getQuestionList())){
            paperQuestionMapper.batchInsert(testPaper.getQuestionList(), testPaper.getId());
        }

    }

    @Override
    public TestPaperBean findTestPaperById(String testPaperId) {
        //参数校验

        //查询试卷
        TestPaperBean testPaper = testPaperMapper.selectTestPaperById(testPaperId);

        //查询试题
        List<PaperQuestionBean> paperQuestionList = paperQuestionMapper.selectByTestPaperId(testPaperId);
        testPaper.setQuestionList(paperQuestionList);

        return testPaper;
    }
}
